package com.common.progress;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 进度条相关
 * @Date: 2025/7/28 13:46
 */
public class ProgressManager {

    private ProgressManager(){

    }

    public static ProgressManager getInstance(){
        return new ProgressManager();
    }

    private final ConcurrentHashMap<String, AtomicInteger> progressMap = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, Integer> totalStepsMap = new ConcurrentHashMap<>();

    // 注册新进度条
    public void registerProgressBar(String taskId, int totalSteps) {
        progressMap.putIfAbsent(taskId, new AtomicInteger(0));
        totalStepsMap.putIfAbsent(taskId, totalSteps);
    }

    // 更新进度
    public void updateProgress(String taskId) {
        AtomicInteger current = progressMap.get(taskId);
        if (current != null) {
            current.incrementAndGet();
        }
    }

    public BigDecimal getProgress(String taskId){
        AtomicInteger current = progressMap.get(taskId);
        Integer allSteps = totalStepsMap.get(taskId);
        if (!ObjectUtils.isEmpty(current)){
            int finishSteps = current.get();
            return BigDecimal.valueOf(finishSteps).divide(BigDecimal.valueOf(allSteps)).multiply(BigDecimal.valueOf(100));
        }
        return BigDecimal.ZERO;
    }

}
